package cumeo89.chii.client.ui;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;

public class ImageButton extends Composite {

	private HorizontalPanel container;
	private Image image;
	private Label label;
	private DisplayMode displayMode;
	private boolean enabled = true;

	public ImageButton(AbstractImagePrototype prototype, String text,
			ClickHandler Handler) {
		this(prototype, text, Handler, DisplayMode.IMAGE_ONLY);
	}

	public ImageButton(AbstractImagePrototype prototype, String text,
			ClickHandler handler, DisplayMode displayMode) {
		container = new HorizontalPanel();
		container.setSpacing(2);

		image = prototype.createImage();
		container.add(image);
		container.setCellHorizontalAlignment(image,
				HasHorizontalAlignment.ALIGN_CENTER);
		container.setCellVerticalAlignment(image,
				HasVerticalAlignment.ALIGN_MIDDLE);

		label = new HTML(text);
		container.add(label);
		container.setCellHorizontalAlignment(label,
				HasHorizontalAlignment.ALIGN_CENTER);
		container.setCellVerticalAlignment(label,
				HasVerticalAlignment.ALIGN_MIDDLE);

		initWidget(container);
		sinkEvents(Event.ONCLICK);
		addDomHandler(handler, ClickEvent.getType());

		setDisplayMode(displayMode);
		setEnabled(true);
	}

	/**
	 * @return the displayMode
	 */
	public DisplayMode getDisplayMode() {
		return displayMode;
	}

	/**
	 * @param displayMode
	 *            the displayMode to set
	 */
	public void setDisplayMode(DisplayMode displayMode) {
		this.displayMode = displayMode;
		if (displayMode == DisplayMode.IMAGE_AND_TEXT) {
			label.setVisible(true);
			image.setTitle(null);
		} else {
			label.setVisible(false);
			image.setTitle(label.getText());
		}
	}

	@Override
	public void onBrowserEvent(Event event) {
		if (DOM.eventGetType(event) == Event.ONCLICK && enabled) {
			event.stopPropagation();
			event.preventDefault();
		} else {
			super.onBrowserEvent(event);
		}
	}

	public void setEnabled(boolean enabled) {
		container.setStyleName(enabled ? "imgbutton"
				: "imgbutton-disabled");
		this.enabled = enabled;
	}

	public boolean isEnabled() {
		return enabled;
	}

	public enum DisplayMode {
		IMAGE_ONLY, IMAGE_AND_TEXT
	}

}
